<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8" />
    <meta content="width=device-width, initial-scale=1.0" name="viewport" />

    <title>部门管理 - XX管理系统</title>

    <!-- Favicons -->
    <link href="assets/img/favicon.png" rel="icon" />
    <!-- Vendor CSS Files -->
    <link
      href="assets/vendor/bootstrap/css/bootstrap.min.css"
      rel="stylesheet"
    />
    <link
      href="assets/vendor/bootstrap-icons/bootstrap-icons.css"
      rel="stylesheet"
    />
    <link
      href="assets/vendor/gridjs/dist/theme/mermaid.min.css"
      rel="stylesheet"
    />

    <!-- Template Main CSS File -->
    <link href="assets/css/style.css" rel="stylesheet" />
  </head>

  <body>
    <!-- ======= Header ======= -->
    <header id="header" class="header fixed-top d-flex align-items-center">
      <div class="d-flex align-items-center justify-content-between">
        <a href="index.html" class="logo d-flex align-items-center">
          <img src="assets/img/logo.png" alt="" />
          <span class="d-none d-lg-block">XX管理系统</span>
        </a>
        <i class="bi bi-list toggle-sidebar-btn"></i>
      </div>
      <!-- End Logo -->

      <nav class="header-nav ms-auto">
        <ul class="d-flex align-items-center">
          <li class="nav-item dropdown pe-3">
            <a
              class="nav-link nav-profile d-flex align-items-center pe-0"
              href="#"
              data-bs-toggle="dropdown"
            >
              <img
                src="assets/img/profile-img.jpg"
                alt="Profile"
                class="rounded-circle"
              />
              <span class="d-none d-md-block dropdown-toggle ps-2"
                >用户名</span
              > </a
            ><!-- End Profile Iamge Icon -->
            <ul
              class="dropdown-menu dropdown-menu-end dropdown-menu-arrow profile"
            >
              <li class="dropdown-header">
                <h6>部门名</h6>
                <span>角色名</span>
              </li>
              <li>
                <hr class="dropdown-divider" />
              </li>

              <li>
                <a
                  class="dropdown-item d-flex align-items-center"
                  href="users-profile.html"
                >
                  <i class="bi bi-person"></i>
                  <span>用户设置</span>
                </a>
              </li>
              <li>
                <hr class="dropdown-divider" />
              </li>

              <li>
                <a class="dropdown-item d-flex align-items-center" href="#">
                  <i class="bi bi-gear"></i>
                  <span>注销</span>
                </a>
              </li>
            </ul>
            <!-- End Profile Dropdown Items -->
          </li>
          <!-- End Profile Nav -->
        </ul>
      </nav>
      <!-- End Icons Navigation -->
    </header>
    <!-- End Header -->

    <!-- ======= Sidebar ======= -->
    <aside id="sidebar" class="sidebar">
      <ul class="sidebar-nav" id="sidebar-nav">
        <li class="nav-item">
          <a class="nav-link collapse" href="index.html">
            <i class="bi bi-grid"></i>
            <span>主页</span>
          </a>
        </li>
        <!-- End Dashboard Nav -->
        <li class="nav-item">
          <a
            class="nav-link collapse"
            data-bs-target="#components-nav"
            data-bs-toggle="collapse"
            href="#"
          >
            <i class="bi bi-menu-button-wide"></i><span>系统管理</span
            ><i class="bi bi-chevron-down ms-auto"></i>
          </a>
          <ul
            id="components-nav"
            class="nav-content"
            data-bs-parent="#sidebar-nav"
          >
            <li>
              <a href="system-user.html"
                ><i class="bi bi-circle"></i><span>用户管理</span></a
              >
            </li>
            <li>
              <a href="system-role.html"
                ><i class="bi bi-circle"></i><span>角色管理</span></a
              >
            </li>
            <li>
              <a href="system-dept.html" class="active"
                ><i class="bi bi-circle"></i><span>部门管理</span></a
              >
            </li>
          </ul>
        </li>
        <li class="nav-item">
          <a class="nav-link" href="blank.html">
            <i class="bi bi-file-earmark"></i>
            <span>后台模板页</span>
          </a>
        </li>
        <!-- End Blank Page Nav -->
      </ul>
    </aside>
    <!-- End Sidebar-->

    <main id="main" class="main">
      <div class="pagetitle">
        <nav>
          <ol class="breadcrumb">
            <li class="breadcrumb-item"><a href="index.html">主页</a></li>
            <li class="breadcrumb-item">系统管理</li>
            <li class="breadcrumb-item active">部门管理</li>
          </ol>
        </nav>
      </div>
      <!-- End Page Title -->

      <section class="section">
        <div class="row">
          <div class="col-lg-12">
            <class class="card">
              <div class="card-body">
                <h5 class="card-title">部门列表</h5>
                <!-- 查询表单 -->
                <form
                  id="searchForm"
                  class="row row-cols-lg-auto g-3 mb-3 align-items-center"
                >
                  <div class="col-12">
                    <div class="input-group">
                      名称：<input
                        type="text"
                        class="form-control"
                        name="name"
                        placeholder=""
                        style="height: 30px; border-radius: 0px"
                      />
                    </div>
                  </div>
                  <div class="col-12">
                    <div class="input-group">
                      类型：<input
                        type="text"
                        class="form-control"
                        name="type"
                        placeholder=""
                        style="height: 30px; border-radius: 0px"
                      />
                    </div>
                  </div>
                  <div class="col-12">
                    <select name="enableState" class="form-select">
                      <option disabled selected value="">请选择</option>
                      <option value="启用">启用</option>
                      <option value="停用">停用</option>
                    </select>
                  </div>
                  <div class="col-12">
                    <button type="submit" class="btn btn-primary">
                      <i class="bi bi-search"></i>查询
                    </button>
                    <button type="reset" class="btn btn-secondary">
                      <i class="bi bi-arrow-repeat"></i>重置
                    </button>
                  </div>
                </form>
                <div>
                  <button
                    id="deptAddBtn"
                    type="button"
                    data-bs-toggle="modal"
                    data-bs-target="#deptAddModal"
                    class="btn btn-sm btn-success m-1"
                  >
                    <i class="bi bi-plus"></i>新增
                  </button>
                </div>
                <div id="dataTable"></div>

                <!-- 部门新增模态框  -->
                <div class="modal fade" id="deptAddModal" tabindex="-1">
                  <form id="deptAddForm" class="needs-validation" novalidate>
                    <input type="hidden" class="form-control" />
                    <div class="modal-dialog modal-dialog-centered modal-lg">
                      <div class="modal-content">
                        <div class="modal-header">
                          <h5 class="modal-title">部门新增</h5>
                          <button
                            type="button"
                            class="btn-close"
                            data-bs-dismiss="modal"
                            aria-label="Close"
                          ></button>
                        </div>

                        <!-- 输入框区域 -->
                        <div class="modal-body">
                          <div class="px-5">
                            <div id="alertResetMessage"></div>
                            <div class="row mb-3">
                              <div>上级部门：总公司</div>
                            </div>
                            <div class="row mb-3">
                              &nbsp;&nbsp;&nbsp;名称：
                              <input
                                type="text"
                                class="form-control"
                                name="name"
                                id="name"
                                required
                                style="width: 250px; border-radius: 5px"
                              />
                            </div>
                            <div class="row mb-3">
                              &nbsp;&nbsp;&nbsp;负责人：
                              <input
                                type="text"
                                class="form-control"
                                name="principal"
                                id="principal"
                                required
                                style="width: 240px; border-radius: 5px"
                              />
                            </div>
                          </div>
                          <div
                            class="row mb-3"
                            style="position: absolute; left: 420px; top: 15px"
                          >
                            &nbsp;&nbsp;&nbsp;编号：
                            <input
                              type="text"
                              class="form-control"
                              name="id"
                              id="id"
                              required
                              style="width: 217px; border-radius: 5px"
                            />
                          </div>
                          <div
                            class="row mb-3"
                            style="
                              position: absolute;
                              left: 420px;
                              top: 15px;
                              display: none;
                            "
                          >
                            &nbsp;&nbsp;&nbsp;父级部门id：
                            <input
                              type="text"
                              class="form-control"
                              name="parentId"
                              id="parentId"
                              required
                              value="#"
                              style="width: 217px; border-radius: 5px"
                            />
                          </div>
                          <div
                            class="row mb-3"
                            style="position: absolute; left: 420px; top: 70px"
                          >
                            &nbsp;&nbsp;&nbsp;类型：
                            <div style="margin-top: -30px; margin-left: 53px">
                              <select
                                class="form-select"
                                id="type"
                                name="type"
                                required
                              >
                                <option disabled selected value="">
                                  请选择
                                </option>
                                <option value="总公司">总公司</option>
                                <option value="分公司">分公司</option>
                                <option value="业务部门">业务部门</option>
                                <option value="其他">其他</option>
                              </select>
                            </div>
                          </div>
                          <div
                            class="row mb-3"
                            style="position: absolute; left: 420px; top: 110px"
                          >
                            &nbsp;&nbsp;&nbsp;电话：
                            <input
                              type="text"
                              class="form-control"
                              name="phone"
                              id="phone"
                              required
                              style="width: 217px; border-radius: 5px"
                            />
                          </div>
                          <div
                            class="row mb-3"
                            style="
                              position: absolute;
                              left: 420px;
                              top: 110px;
                              display: none;
                            "
                          >
                            &nbsp;&nbsp;&nbsp;备注：
                            <input
                              type="text"
                              class="form-control"
                              name="remark"
                              id="remark"
                              value=""
                              style="width: 217px; border-radius: 5px"
                            />
                          </div>
                        </div>

                        <div class="modal-footer">
                          <button
                            type="button"
                            class="btn btn-secondary"
                            name="close"
                            data-bs-dismiss="modal"
                          >
                            取消
                          </button>
                          <button type="submit" class="btn btn-primary">
                            确定
                          </button>
                        </div>
                      </div>
                    </div>
                  </form>
                </div>

                <!-- 部门编辑模态框 -->
                <div class="modal fade" id="deptEditModal" tabindex="-1">
                  <form id="deptEditForm" class="needs-validation" novalidate>
                    <input type="hidden" class="form-control" />
                    <div class="modal-dialog modal-dialog-centered modal-lg">
                      <div class="modal-content">
                        <div class="modal-header">
                          <h5 class="modal-title">部门编辑</h5>
                          <button
                            type="button"
                            class="btn-close"
                            data-bs-dismiss="modal"
                            aria-label="Close"
                          ></button>
                        </div>

                        <div class="modal-body">
                          <div class="px-5">
                            <div id="alertResetMessage"></div>
                            <div class="row mb-3">
                              <div>上级部门：总公司</div>
                            </div>
                            <div class="row mb-3">
                              &nbsp;&nbsp;&nbsp;名称：
                              <input
                                type="text"
                                class="form-control"
                                name="name"
                                id="name"
                                required
                                style="width: 250px; border-radius: 5px"
                              />
                            </div>
                            <div class="row mb-3">
                              &nbsp;&nbsp;&nbsp;负责人：
                              <input
                                type="text"
                                class="form-control"
                                name="principal"
                                id="principal"
                                required
                                style="width: 240px; border-radius: 5px"
                              />
                            </div>
                          </div>

                          <div
                            class="row mb-3"
                            style="position: absolute; left: 420px; top: 15px"
                          >
                            <div>编号：<span id="id1"></span></div>
                            <input
                              type="text"
                              id="id2"
                              name="id"
                              style="display: none"
                            />
                          </div>

                          <div
                            class="row mb-3"
                            style="position: absolute; left: 420px; top: 70px"
                          >
                            &nbsp;&nbsp;&nbsp;类型：
                            <div style="margin-top: -30px; margin-left: 53px">
                              <select class="form-select" id="type" name="type">
                                <option disabled value="">请选择</option>
                                <option value="总公司">总公司</option>
                                <option value="分公司">分公司</option>
                                <option value="业务部门">业务部门</option>
                                <option value="其它">其它</option>
                              </select>
                            </div>
                          </div>
                          <div
                            class="row mb-3"
                            style="position: absolute; left: 420px; top: 110px"
                          >
                            &nbsp;&nbsp;&nbsp;电话：
                            <input
                              type="text"
                              class="form-control"
                              name="phone"
                              id="phone"
                              required
                              style="width: 217px; border-radius: 5px"
                            />
                          </div>
                          <div
                            class="row mb-3"
                            style="
                              position: absolute;
                              left: 420px;
                              top: 110px;
                              display: none;
                            "
                          >
                            &nbsp;&nbsp;&nbsp;备注：
                            <input
                              type="text"
                              class="form-control"
                              name="remark"
                              id="remark"
                              style="width: 217px; border-radius: 5px"
                            />
                          </div>
                        </div>

                        <div class="modal-footer">
                          <button
                            type="button"
                            class="btn btn-secondary"
                            name="close"
                            data-bs-dismiss="modal"
                          >
                            取消
                          </button>
                          <button type="submit" class="btn btn-primary">
                            确定
                          </button>
                        </div>
                      </div>
                    </div>
                  </form>
                </div>
              </div>
            </class>
          </div>
        </div>
      </section>

      <div class="toast-container position-fixed right-0 top-0 end-0">
        <div
          id="liveToast"
          class="toast"
          role="alert"
          aria-live="assertive"
          aria-atomic="true"
        >
          <div
            class="toast-body"
            id="toast-body"
            style="
              box-sizing: border-box;
              width: 100%;
              background: #409eff19;
              border-left: 5px solid #0d6efd;
            "
          >
            修改成功
          </div>
        </div>
      </div>
    </main>
    <!-- End #main -->

    <!-- ======= Footer ======= -->
    <footer id="footer" class="footer">
      <div class="copyright">
        &copy; Copyright <strong><span>XX管理系统</span></strong
        >. All Rights Reserved
      </div>
      <div class="credits">
        Designed by 2022030102080 庄先琪
        <a href="https://bootstrapmade.com/">BootstrapMade</a>
      </div>
    </footer>
    <!-- End Footer -->

    <a
      href="#"
      class="back-to-top d-flex align-items-center justify-content-center"
      ><i class="bi bi-arrow-up-short"></i
    ></a>

    <!-- Vendor JS Files -->
    <script src="assets/vendor/bootstrap/js/bootstrap.bundle.min.js"></script>
    <script src="assets/vendor/gridjs/dist/gridjs.umd.js"></script>
    <script src="assets/vendor/gridjs/I10n/dist/l10n.umd.js"></script>
    <script src="assets/vendor/moment/moment.js"></script>
    <!-- <script src="assets/vendor/bootstrap-icons/bootstrap-icons.json"></script>
    <script src="assets/vendor/bootstrap/js/bootstrap.bundle.js"></script> -->
    <!-- <script src="assets/vendor/bootstrap/js/bootstrap.bundle.min.js.map"></script> -->
    <!-- Template Main JS File -->
    <script src="assets/js/main.js"></script>
    <script>
      function addQueryParam(url, param) {
        // 如果URL中已经有查询参数，则使用"&"来添加新参数
        // 如果没有，则使用"?"来添加第一个参数
        let separator = url.indexOf("?") !== -1 ? "&" : "?";
        // 添加参数到URL
        return url + separator + param;
      }
      const url = "/api/rest/dept/all";
      let data = [];
      const columns = [
        {
          id: "name",
          name: "名称",
        },
        {
          id: "id",
          name: "编号",
        },
        {
          id: "type",
          name: "类型",
        },
        {
          id: "enableState",
          name: "状态",
        },
        {
          id: "principal",
          name: "负责人",
        },
        {
          id: "phone",
          name: "电话",
        },
        {
          id: "updateAt",
          name: "更新时间",
        },
        {
          name: "操作",
          width: "25%",
          formatter: (cell, row) => {
            const enableState = row.cells[5].data;
            const index = row.cells[0].data;
            const toggleButtonHtml =
              enableState === "启用"
                ? `<button id="roleDisableBtn" type="button" class="btn btn-sm btn-danger m-1" data-index="${index}">
              <i class="bi bi-person-slash"></i>停用
              </button>`
                : `<button id="roleEnableBtn" type="button" class="btn btn-sm btn-success m-1" data-index="${index}">
              <i class="bi bi-person-check"></i>启用
              </button>`;

            return gridjs.html(`
              <button id="deptEditBtn" type="button" class="btn btn-sm btn-warning m-1">
                  <i class="bi bi-pencil-square" ></i>修改
              </button>
            ${toggleButtonHtml}
          `);
          },
        },
      ];
      const server = {
        url,
        then: (data) => {
          return data.map((item) => [
            item.name,
            item.id,
            item.type,
            item.enableState,
            item.principal,
            item.phone,
            item.updateAt
              ? moment(item.updateAt).format("YYYY-MM-DD hh:mm:ss")
              : "",
          ]);
        },
        total: (data) => data.totalElements,
      };
      const pagination = {
        limit: 10,
        server: {
          url: (prev, page, limit) =>
            addQueryParam(prev, `size=${limit}&page=${page}`),
        },
      };
      const options = {
        columns,
        server,
        pagination,
        language: gridjs.l10n.cnCN,
      };

      window.onload = function () {
        // toats
        const toastLiveExample = document.getElementById("liveToast");
        const toastBody = document.getElementById("toast-body");
        const toastBootstrap =
          bootstrap.Toast.getOrCreateInstance(toastLiveExample);

        // 模态窗
        let deptAddDom = document.getElementById("deptAddModal");
        let deptAddModal = new bootstrap.Modal(deptAddDom, {
          keyboard: false,
        });
        let deptEditDOM = document.getElementById("deptEditModal");
        let deptEditModal = new bootstrap.Modal(deptEditDOM, {
          keyboard: false,
        });

        const grid = new gridjs.Grid(options);
        grid.render(dataTable);

        searchForm.addEventListener("submit", (event) => {
          event.preventDefault();
          const formData = new FormData();
          formData.set("name", searchForm.name.value.trim());

          formData.set("type", searchForm.type.value.trim());
          formData.set("enableState", searchForm.enableState.value);

          const searchParams = new URLSearchParams(formData);
          options.server.url = addQueryParam(url, searchParams.toString());
          grid.updateConfig(options).forceRender();
        });

        grid.on("cellClick", (...args) => {
          const event = args[0];
          event.preventDefault();
          if (event.target?.id === "deptEditBtn") {
            const cells = args[3].cells;
            deptEditDOM.querySelector("#name").value = cells[0].data;
            deptEditDOM.querySelector("#id1").innerHTML = cells[1].data;
            deptEditDOM.querySelector("#id2").value = cells[1].data;
            deptEditDOM.querySelector("#type").value = cells[2].data;
            deptEditDOM.querySelector("#principal").value = cells[4].data;
            deptEditDOM.querySelector("#phone").value = cells[5].data;
            console.log(cells);
            deptEditModal.show();
          }
        });

        // 部门新增表单操作
        deptAddForm.addEventListener("submit", (event) => {
          event.preventDefault();
          if (deptAddForm.checkValidity()) {
            console.log("填写校验通过");
            const formData = Object.fromEntries(new FormData(deptAddForm));
            console.log(formData);
            fetch(`/api/rest/dept`, {
              method: "POST",
              headers: { "Content-Type": "application/json" },
              body: JSON.stringify(formData),
            }).then((response) => {
              if (response.ok) {
                // 关闭模态窗
                deptAddModal.hide();
                // 提示信息
                toastBody.innerHTML = "添加成功";
                toastBootstrap.show();
                //重新加载表格
                grid.updateConfig(options).forceRender();
              }
            });
          }
        });

        // 部门修改表单操作
        deptEditForm.addEventListener("submit", (event) => {
          event.preventDefault();
          if (deptEditForm.checkValidity()) {
            const formData = Object.fromEntries(new FormData(deptEditForm));
            const encodedId = encodeURIComponent(formData.id);
            fetch("/api/rest/dept/" + encodedId, {
              method: "PATCH",
              headers: { "Content-Type": "application/json" },
              body: JSON.stringify(formData),
            }).then((response) => {
              console.log(response);
              if (response.ok) {
                deptEditModal.hide();
                toastBody.innerHTML = "修改成功";
                toastBootstrap.show();
                grid.updateConfig(options).forceRender();
              }
            });
          }
          //
        });
      };
    </script>
  </body>
</html>
